<?php
// +----------------------------------------------------------------------
// | NewThink [ Think More,Think Better! ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2018 http://www.newthink.cc All rights reserved.
// +----------------------------------------------------------------------
// | 版权所有：山西创泰网络科技有限公司
// +----------------------------------------------------------------------
// | Author: JiYun Date:2019-02-28 Time:16:42
// +----------------------------------------------------------------------

namespace app\common\service;

use PhpOffice\PhpSpreadsheet\Spreadsheet;

/**
 * Class BaseService
 * @package app\index\service
 */
class BaseService
{
    public $pdo;
    public $mongodb;

    /**
     * 构造函数
     * SourceList constructor.
     */
    public function __construct()
    {
        try {
            //mysql
            $this->pdo = new \PDO('mysql:host=rm-bp11r52xk5623pn66o.mysql.rds.aliyuncs.com;dbname=huanxin', 'huanxin', 'Sxctkjhuanxin!');   //mysql连接数据库
            $this->pdo->setAttribute(\PDO::ATTR_ERRMODE, \PDO::ERRMODE_EXCEPTION);   //设置错误处理模式
            //mongodb
            $uri = 'mongodb://root:Ws4815115!@dds-bp1babc036f87d64-pub.mongodb.rds.aliyuncs.com:3717';
            $this->mongodb = new\MongoDB\Driver\Manager($uri);   //mongodb连接数据库
        } catch (PDOException $e) {
            var_dump($e);
            die;
        }
    }

    /**
     * +----------------------------------------------------------
     * 插入定时任务日志表
     * @param string $cronName 定时任务英文名称
     * @param string $cronStartTime 定时任务开始时间
     * @param string $filename 文件名
     * @param integer $status 状态1完成0未完成
     * @param string $cronMemo 定进任务备注
     * +----------------------------------------------------------
     * @example $cronName reductionGidList, $cronMemo 预案-动态网格数据
     * @author hongwei 201-05-29
     * +----------------------------------------------------------
     */
    public function insertTaskLogTable($cronName, $cronStartTime, $filename, $status, $cronMemo)
    {
        try {
            $sql  = 'insert into system_task_log(name,region_id,start_time,end_time,length,status,description,filename) values ';
            $sql  .= '(?, ?, ?, ?, ?, ?, ?, ?)';
            $stmt = $this->pdo->prepare($sql);
            //绑定参数
            $stmt->bindValue(1, $cronName);
            $stmt->bindValue(2, '53');
            $stmt->bindValue(3, $cronStartTime);
            $cronEndTime = time();
            $stmt->bindValue(4, $cronEndTime);
            $stmt->bindValue(5, $cronEndTime - $cronStartTime);
            $stmt->bindValue(6, $status);
            $stmt->bindValue(7, $cronMemo);
            $stmt->bindValue(8, $filename);
            $stmt->execute();
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }


    /**
     * +----------------------------------------------------------
     * 获取气象局的目录
     * @param string $rootDir 气象局根目录
     * @param string $pathDirDate 气象局二级目录，默认为日期目录，如day是日期，输入日期为指定日期
     * +----------------------------------------------------------
     * @return string
     * @author hongwei 2019-06-26
     * +----------------------------------------------------------
     */
    public function getBureauPath($rootDir, $pathDirDate = 'day')
    {
        $os_name = PHP_OS;

        //日期目录
        if ($pathDirDate == 'day') {
            $pathDirDate = date('Y-m-d', strtotime('-1 day'));
        } else {
            $pathDirDate = date('Y-m-d', strtotime($pathDirDate));
        }

        //判断操作系统运行不同的目录
        $savePath = '';
        if (strpos($os_name, "Linux") !== false) {
            $savePath = '/www/wwwroot/ftproot/bureau/' . $rootDir . '/' . $pathDirDate;
        } elseif (strpos($os_name, "WIN") !== false) {
            $savePath = 'c:/ftp/ftproot/' . $rootDir . '/' . $pathDirDate;
        }
        return $savePath;
    }

    /**
     * 方案目录名称
     * @author hongwei 2019-07-06
     * @param $rootDir
     * @param $tsinghuaPlanName
     * @return string
     */
    public function getBureauTsinghuaPlanPath($rootDir, $tsinghuaPlanName)
    {
        $os_name = PHP_OS;
        //判断操作系统运行不同的目录
        $savePath = '';
        if (strpos($os_name, "Linux") !== false) {
            $savePath = '/www/wwwroot/ftproot/bureau/' . $rootDir . '/' . $tsinghuaPlanName;
        } elseif (strpos($os_name, "WIN") !== false) {
            $savePath = 'c:/ftp/ftproot/' . $rootDir . '/' . $tsinghuaPlanName;
        }
        return $savePath;
    }

    /**
     * +----------------------------------------------------------
     * 导出数据
     * @param array $arrDataFrom 数据来源
     * @param array $arrTableTitle 表格的头部
     * @param string $savePath 保存路径
     * @param string $saveFilename 保存的文件名
     * @param integer $dataStartRow 保存开始的行
     * @param bool $startDate 是否有开始日期
     * @param bool $isWebDown 是否网页保存
     * +----------------------------------------------------------
     * @example 网格 $arrTableTitle = ['nrow', 'ncol', 'BC', 'CO', 'NOX', 'OC', 'PM10', 'PM2.5', 'SO2', 'VOC', 'CO2', 'NH3', 'TSP'];
     * @example 源清单 $arrTableTitle = ['企业ID号', '排口号', '经度', '纬度', 'BC', 'CO', 'NOx', 'OC', 'PM10', 'PM2.5', 'SO2', 'VOC', 'CO2', 'NH3', 'TSP'];
     * @author hongwei 2019-05-29 刚开始建立的
     * @author hongwei 2019-07-02 封装为方法
     * +----------------------------------------------------------
     */
    public function exportData($arrDataFrom, $arrTableTitle, $savePath, $saveFilename, $dataStartRow = 2, $startDate = false, $isWebDown = false)
    {
        try {
            //初始相关excel信息
            $spreadsheet = new Spreadsheet();
            $worksheet   = $spreadsheet->getActiveSheet();

            //step2:将标题放入excel中
            if ($startDate) {
                //step2:将开始减排日期放入第一行
                $rowIndex0       = 1; //第1行
                $columnIndex0    = 1; //第0列
                $worksheet->setCellValueByColumnAndRow($columnIndex0, $rowIndex0, $startDate); //单元内填充
                unset($columnIndex0, $rowIndex0);
            }

            //step2:将标题放入excel中
            $rowIndex       = $dataStartRow - 1; //第2行
            $columnIndex    = 0; //第0列
            foreach ($arrTableTitle as $k => $v) {
                $columnIndex++; //第1列，第2列..
                $worksheet->setCellValueByColumnAndRow($columnIndex, $rowIndex, $arrTableTitle[$k]); //单元内填充
            }
            unset($columnIndex, $rowIndex);


            //step3:将数据放入excel中
            $columnIndex2 = 0; //第1列
            foreach ($arrDataFrom as $key => $value) {
                foreach ($value as $k => $v) {
                    $columnIndex2++;
                    $worksheet->setCellValueByColumnAndRow($columnIndex2, $dataStartRow, $value[$k]); //单元内填充
                }
                $dataStartRow++;
                $columnIndex2 = 0;
            }
            unset($columnIndex2, $rowIndex2);

            //step4:保存excel并导出
            $writer = \PhpOffice\PhpSpreadsheet\IOFactory::createWriter($spreadsheet, 'Csv');
            /* Set CSV parsing options */
            $writer->setDelimiter(','); //设置用逗号隔开
            $writer->setEnclosure(''); //设置不要引号

            //step5:网页下载,测试使用
            if ($isWebDown) {
                header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
                header('Content-Disposition: attachment;filename="' . $saveFilename . '"');
                header('Cache-Control: max-age=0');
                $writer->save('php://output');
                exit;
            }

            //step6:生成目录并移动文件
            $savePathFile = $savePath . DIRECTORY_SEPARATOR . $saveFilename;
            if (is_dir($savePath) || @mkdir($savePath, 0777)) {
                @mkdir($savePath, 0777);
            }
            $writer->save($savePathFile);
        } catch (\Exception $e) {
            die($e->getMessage());
        }
    }

    /**
     * 获取单列信息
     * @author hongwei 2019-07-17
     * @param $sql
     * @return mixed
     */
    public function pdoFetchColumn($sql)
    {
        $sth = $this->pdo->prepare($sql);
        $sth->execute();
        $result = $sth->fetchColumn();
        return $result;
    }

    /**
     * 获取查询单条结果
     * @param $sql
     * @return mixed
     */
    public function pdoFetch($sql)
    {
        $sth = $this->pdo->prepare($sql);
        $sth->execute();
        $result = $sth->fetch();
        return $result;
    }

    /**
     * 获取所有查询结果
     * @author
     * @param $sql
     * @return array
     */
    public function pdoFetchAll($sql)
    {
        $sth = $this->pdo->prepare($sql);
        $sth->execute();
        $result = $sth->fetchAll();
        return $result;
    }
}
